const { BrowserWindow, screen,ipcMain } = require("electron");
require('@electron/remote/main').initialize();

const path = require("path");
const { isDev } = require("./utils.cjs");
const logger = require("./log.cjs");
const windowManager = require("./windowMamager.cjs");
function setWindowInit() {
  try {
    windowManager.add("settingWin", settingWindow);
    // 创建一个托盘实例，并指定图标的路径
    let setWin = settingWindow();
    setWin.loadURL(
      isDev()
        ? "http://localhost:5173/#/setting"
        : `file://${path.join(__dirname, "../dist/index.html")}#/setting`
    );
  } catch (error) {
    logger.error(error);
  }
}

const settingWindow = () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  const primaryDisplay = screen.getPrimaryDisplay();
  const scaleFactor = primaryDisplay.scaleFactor;
  windowWidth = 300;
  windowHeight = 280;
  const x = parseInt((width - windowWidth) / scaleFactor); // 窗口的水平位置
  const y = parseInt((height - windowHeight) / scaleFactor); // 窗口的垂直位置
  win = new BrowserWindow({
    width: windowWidth,
    height: windowHeight,
    center: true,
    x,
    y,
    skipTaskbar: false,
    resizable: false,
    frame: false,
    show: false,
    autoHideMenuBar: true,
    alwaysOnTop: false,
    webPreferences: {
      contextIsolation: false,
      webSecurity: false,
      //  渲染进程 开启node模块，使得JS中可以使用node的model
      nodeIntegration: true,
      // 开启 remote 模块
      enableBlinkFeatures: true,
      enableRemoteModule: true,//开启remote模块
      // 控制上下文隔离
      // contextIsolation:false,
    },
  });
  windowManager.add("settingWin", win);
  win.setSkipTaskbar(true);
  handleIPC();
  require("@electron/remote/main").enable(win.webContents)
  // win.webContents.openDevTools();
  return win;
};

function handleIPC() {
  ipcMain.handle("close-setting", function (e, ...args) {
    let setWin = windowManager.get("settingWin");
    let search = windowManager.get("searchWin");
    search.setAlwaysOnTop(args[0]||false);
    setWin.hide();
    search.show();
  });
}

module.exports = {
  setWindowInit,
};
